import sublime
import sublime_plugin
import re
import http.client
import hashlib
import urllib
import random
import json
import threading
import urllib.request as request
import urllib.parse  as urlparse
from .config import appid, secretKey
from xml.dom.minidom import parseString
from copy import deepcopy

def baidu_translate(word):
    myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
    from_lang = 'auto'
    to_lang = 'en'
    salt = random.randint(32768, 65536)
    sign = appid + word + str(salt) + secretKey
    sign = hashlib.md5(sign.encode(encoding="utf-8")).hexdigest()
    
    data = {
        'from': from_lang,
        'to': to_lang,
        'appid': appid,
        'salt': str(salt),
        'sign': sign,
        'q': word
    }
    data = urllib.parse.urlencode(data)
    url = '%s?%s' % (myurl, data)
    res = urllib.request.urlopen(url)
    result = str(res.read(), encoding='utf-8',errors='ignore')
    result = json.loads(result)
    if result.get('error_code') is None:
        result_s = []
        for s in result['trans_result']:
            result_s.append(s['dst'])
        result_s = '\n'.join(result_s)
        return result_s
    elif result.get('error_code') == '52003':
        sublime.error_message('???appid')
    else:
        return None

def just_translate(string):
    #result = baidu_translate(string)
    dst = baidu_translate(string)
    return dst

global_thread_flag = 1

class ThreadRun(threading.Thread):
    '''class docs'''
    def __init__(self,fetch_func, render_func, args=[], render_args=[], thread_flag=0):
        '''init docs'''
        super(ThreadRun, self).__init__()
        self.setDaemon(True)
        self.fetch_func = fetch_func
        self.render_func = render_func
        self.args = args
        self.render_args = render_args
        self.thread_flag = thread_flag

    def run(self):
        if self.args:
            result = self.fetch_func(*self.args)
        else:    
            result = self.fetch_func()
         
        if self.thread_flag != global_thread_flag:
            return
        else:
            pass

        if self.render_args:
            self.render_func(result,*self.render_args)
        else:    
            self.render_func(result)

class TranslatorCallbackCommand(sublime_plugin.TextCommand):
    def run(self,edit,start,endl,result):
        cur_region=sublime.Region(start, endl)
        #不能直接传region
        self.view.replace(edit,cur_region,result)

class LoeTranslatorCommand(sublime_plugin.TextCommand):

    def is_chinese(self, ch):
        if type(ch) != str: return False
        return '\u4e00' <= ch <= '\u9fff'

    def check_key(self):
        if appid == '' or secretKey == '':
            sublime.error_message('To api.fanyi.baidu.com Get appid and ecretKey,and config.py')
            return False
        return True

    @property
    def current_word(self):
        #For the selected field word
        #or the matching word near the cursor
        current_region = self.view.sel()[0]
        if current_region.a != current_region.b:
            prefix=""
            return current_region,prefix,self.view.substr(current_region)
        else :
            #word = self.view.word(current_region)
            line_region = self.view.line(current_region)
            ans_string = self.view.substr(line_region)
            prefix=""
            for ch in ans_string:
                if self.is_chinese(ch):
                    index = ans_string.find(ch)
                    tmp=ans_string
                    ans_string = ans_string[index:]
                    prefix = "" if index == 0 else tmp[0: index]
                    return line_region,prefix,ans_string
                else :
                    pass
            return line_region,prefix,ans_string

    def render_popup(self,result,region,prefix):
        global global_thread_flag
        global_thread_flag -= 1
        result=prefix+result
        #print(type(region))
        self.view.run_command("translator_callback",
                             {"start":region.a,"endl":region.b,"result":result})
        #self.view.replace(edit,region,result)

    def run(self, edit):
        #Judge whether the appid and key of the user are correct
        if not self.check_key():
            return
        else :
            pass

        global global_thread_flag
        global_thread_flag += 1
        flag = deepcopy(global_thread_flag)
        choose_line,prefix,edit_string=self.current_word
        
        ThreadRun(  just_translate, 
                    self.render_popup, 
                    [edit_string],
                    [choose_line,prefix],
                    thread_flag=flag).start()
        # res=just_translate(edit_string)
        # self.render_popup(prefix+res)
        #中文 英文
        #更改名字，更改键位
        #如果不是utf8，添加忽略
